package com.taichuan.selfcheck.ui.fragment;

import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.taichuan.keysupport.Key;
import com.taichuan.keysupport.view.KSSpinner;
import com.taichuan.keysupport.view.panel.TcPanelEditText;
import com.taichuan.selfcheck.R;
import com.taichuan.selfcheck.mvp.presenter.PingPresenter;
import com.taichuan.selfcheck.mvp.viewinterface.PingInterface;
import com.taichuan.selfcheck.persistent.PersistentManager;
import com.taichuan.selfcheck.ui.activity.base.AppBaseActivity;
import com.taichuan.selfcheck.ui.fragment.base.AppBaseFragment;
import com.taichuan.selfcheck.utils.UrlUtils;
import com.taichuan.tcutils.taichuan.SystemUtils;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 该类主要用于
 *
 * @author CamelLuo
 * @version 2020/1/7
 */
public class NetworkTestFragment extends AppBaseFragment<PingInterface, PingPresenter> implements PingInterface {
    private static final String TAG = NetworkTestFragment.class.getSimpleName();

    @BindView(R.id.fragment_network_test_url_test_editText)
    TcPanelEditText testIpEt;
    @BindView(R.id.fragment_network_test_check_button)
    Button checkIpBtn;
    @BindView(R.id.fragment_network_test_ip_address_textView)
    TextView ethernetIpAddressTv;
    @BindView(R.id.fragment_network_test_ethernet_state_imageView)
    ImageView ethernetStateIv;
    @BindView(R.id.fragment_network_test_result_textView)
    TextView testIpResultTv;
    @BindView(R.id.fragment_network_test_ip_type_spinner)
    KSSpinner urlSelectSp;
    @BindView(R.id.fragment_network_test_check_iot_sdk_mqtt_connect_state_button)
    Button checkIotSdkMqttConnectStateBtn;
    @BindView(R.id.fragment_network_test_iot_sdk_mqtt_connect_state_result_textView)
    TextView iotSdkMqttConnectStateResultTv;
    @BindView(R.id.tips_textView)
    TextView tipsTv;

    private String[] urlTypeValueArray;
    private String[] urlTypeNameArray;

    @Override
    protected boolean isAllowAutoFinishFragment() {
        return false;
    }

    @Override
    public void doOnAutoFinishFragment() {
        if (!((AppBaseActivity) mActivity).getIsTouchDevice()) {       // 按键设备
            // TODO 按键设备，在编辑框和下拉框取得焦点时 ，禁止返回操作
            if (!testIpEt.isFocused() && !urlSelectSp.isFocused()) {
                operateFragmentManagerBack();
            }
        } else {                     // 触屏设备
            operateFragmentManagerBack();
        }
    }

    @Override
    protected void getBundleValues(Bundle bundle) {

    }

    @Override
    protected int setContentViewId() {
        //不管是12键还是16键的设备，全部统一使用12键的控件
        return R.layout.fragment_test_network;
    }

    @Override
    protected void initView(View view, Bundle bundle) {
        tipsTv.setText(Html.fromHtml(getString(R.string.ctrl_tips_function)));
        testIpEt.init(getContext(), ((AppBaseActivity) mActivity).getIsTouchDevice());
        initSpnner();
        if(!SystemUtils.isTouchDevice()){
            initFocus();
        }
    }

    /**
     * 定义一个方法用于初始化 常用url地址选择Spinner
     */
    private void initSpnner() {
        //获取下拉列表显示内容的结果值数组
        urlTypeValueArray = mActivity.getResources().getStringArray(R.array.network_test_url_type_value);
        urlTypeNameArray = mActivity.getResources().getStringArray(R.array.network_test_url_type_name);

        urlSelectSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (urlTypeValueArray != null && urlTypeValueArray.length > 0 && position <= urlTypeValueArray.length) {
                    if (urlTypeNameArray != null && urlTypeNameArray.length > 0 && position <= urlTypeNameArray.length) {
                        showMsg("选中了 " + urlTypeNameArray[position] + " 请按(#/OK/✔)键确认选择");
                    }

                    //获取点击的内容
                    if (position == 3) {         //门口机所登录的云平台
                        //获取门口机所登录的云平台地址
                        String cloudPlatformUrl = PersistentManager.get().getCloudPlatformUrl();
                        if (!TextUtils.isEmpty(cloudPlatformUrl)) {
                            testIpEt.setText(UrlUtils.getUrlCanPing(cloudPlatformUrl));
                            //设置文本后要将光标移至末尾
                            if (!TextUtils.isEmpty(testIpEt.getText().toString())) {
                                Log.i(TAG, "initView: 将光标移至末尾");
                                testIpEt.setSelection(testIpEt.length());
                            }
                        } else {
                            showMsg("本次启动未传入门口机云平台地址，无法测试，请手动填入");
                        }
                    } else {                     //常规网址
                        String urlTypeValue = urlTypeValueArray[position];
                        testIpEt.setText(urlTypeValue);
                        //设置文本后要将光标移至末尾
                        if (!TextUtils.isEmpty(testIpEt.getText().toString())) {
                            Log.i(TAG, "initView: 将光标移至末尾");
                            testIpEt.setSelection(testIpEt.length());
                        }
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void initFocus() {
        mViewFocus.removeAll();
        mViewFocus.add(checkIpBtn);
        mViewFocus.add(checkIotSdkMqttConnectStateBtn);
        mViewFocus.add(urlSelectSp);
        mViewFocus.add(testIpEt);
        mViewFocus.requestFocus(checkIpBtn);
    }

    @OnClick({R.id.fragment_network_test_check_button, R.id.fragment_network_test_check_iot_sdk_mqtt_connect_state_button})
    @Override
    protected void onXmlClick(View v) {
        super.onXmlClick(v);
        switch (v.getId()) {
            case R.id.fragment_network_test_check_button: {
                //关闭软键盘
                hiddenSoftKeyboard();
                mPresenter.checkIpCanPing(testIpEt.getText().toString().trim().replace(" ", ""));
                break;
            }
            case R.id.fragment_network_test_check_iot_sdk_mqtt_connect_state_button: {
                //关闭软键盘
                hiddenSoftKeyboard();
                mPresenter.checkDeviceMqttConnectState();
                break;
            }
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (mViewFocus.onFocused(testIpEt) ||
                mViewFocus.onFocused(urlSelectSp)) {           //当焦点在EditText,Spinner 等控件时
            if (event.getKeyCode() == Key.Convert.KEYCODE_LONG_XING) {
                mViewFocus.nextFocus();
            } else {
                mViewFocus.handleClick();
            }
            //直接返回false让焦点控件消费掉按键事件，不再通知上级控件消费处理
            return false;
        } else {                                             //当不处于特殊焦点控件时
            switch (event.getKeyCode()) {
                case Key.Convert.KEYCODE_1:
                    checkIpBtn.performClick();
                    break;
                case Key.Convert.KEYCODE_2:
                    checkIotSdkMqttConnectStateBtn.performClick();
                    break;
                case Key.Convert.KEYCODE_LONG_XING:
                    mViewFocus.nextFocus();
                    break;
                case Key.Convert.KEYCODE_JING:
                    mViewFocus.handleClick();
                    break;
                case Key.Convert.KEYCODE_XING: {
                    Log.i(TAG, "dispatchKeyEvent: 点击了返回键，退出页面");
                    appBaseActivity.clickBackKey();
                    //该Fragment的返回键事件交由其自身处理，不再通知上级控件消费处理
                    return true;
                }
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected PingPresenter createPresenter() {
        return new PingPresenter();
    }

    @Override
    public void showPingResult(boolean isSucess, String pingResult) {
        if (isSucess) {

        } else {

        }

        if (testIpResultTv != null) {
            testIpResultTv.setText(pingResult);
        }
    }

    @Override
    public void showManagerConnectState(boolean isSucess, String stateResule) {

    }

    @Override
    public void checkMqttConnectStateResult(boolean isSucess, String result) {
        showMsg(isSucess ? "连接正常" : "连接失败");
        if (iotSdkMqttConnectStateResultTv != null) {
            iotSdkMqttConnectStateResultTv.setText(result);
        }
    }

    @Override
    public void showLoading() {
        mActivity.showStaticDialog("正在测试，请耐心等候");
    }
}
